<template>
  <div class="retail-products">
    <div class="page-header">
      <h2>商品管理</h2>
      <p>管理零售商品信息，包括商品分类、价格、库存等</p>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品编码">
          <el-input v-model="searchForm.code" placeholder="请输入商品编码" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="食品饮料" value="food" />
            <el-option label="服装鞋帽" value="clothing" />
            <el-option label="电子产品" value="electronics" />
            <el-option label="家居用品" value="home" />
            <el-option label="美妆护肤" value="beauty" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" value="active" />
            <el-option label="下架" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('retail:product:add')">
        <el-icon><Plus /></el-icon>新增商品
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="warning" @click="handleBatchUpdate">批量操作</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card">
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ getCategoryText(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="price" label="售价" width="100">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="costPrice" label="成本价" width="100">
          <template #default="{ row }">
            ¥{{ row.costPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(row)"
              v-if="hasPermission('retail:product:edit')"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              v-if="hasPermission('retail:product:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入商品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="食品饮料" value="food" />
                <el-option label="服装鞋帽" value="clothing" />
                <el-option label="电子产品" value="electronics" />
                <el-option label="家居用品" value="home" />
                <el-option label="美妆护肤" value="beauty" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="售价" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input-number v-model="form.costPrice" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number v-model="form.stock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位" style="width: 100%">
                <el-option label="个" value="个" />
                <el-option label="件" value="件" />
                <el-option label="包" value="包" />
                <el-option label="瓶" value="瓶" />
                <el-option label="盒" value="盒" />
                <el-option label="套" value="套" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="active">上架</el-radio>
            <el-radio value="inactive">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 搜索表单
const searchForm = reactive({
  code: '',
  name: '',
  category: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  category: '',
  brand: '',
  price: 0,
  costPrice: 0,
  stock: 0,
  unit: '',
  description: '',
  status: 'active'
})

// 表单验证规则
const formRules = {
  code: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
  costPrice: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    code: 'P001',
    name: '可口可乐',
    category: 'food',
    brand: '可口可乐',
    price: 3.50,
    costPrice: 2.80,
    stock: 500,
    unit: '瓶',
    description: '经典碳酸饮料',
    status: 'active',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    code: 'P002',
    name: 'iPhone 15',
    category: 'electronics',
    brand: 'Apple',
    price: 5999.00,
    costPrice: 4800.00,
    stock: 50,
    unit: '台',
    description: '最新款智能手机',
    status: 'active',
    createTime: '2024-01-14 14:20:00'
  },
  {
    id: 3,
    code: 'P003',
    name: 'Nike运动鞋',
    category: 'clothing',
    brand: 'Nike',
    price: 299.00,
    costPrice: 180.00,
    stock: 200,
    unit: '双',
    description: '舒适运动鞋',
    status: 'active',
    createTime: '2024-01-13 09:15:00'
  },
  {
    id: 4,
    code: 'P004',
    name: 'SK-II神仙水',
    category: 'beauty',
    brand: 'SK-II',
    price: 1599.00,
    costPrice: 1200.00,
    stock: 30,
    unit: '瓶',
    description: '高端护肤精华',
    status: 'active',
    createTime: '2024-01-12 16:45:00'
  },
  {
    id: 5,
    code: 'P005',
    name: '宜家台灯',
    category: 'home',
    brand: 'IKEA',
    price: 89.00,
    costPrice: 60.00,
    stock: 150,
    unit: '个',
    description: '简约现代台灯',
    status: 'active',
    createTime: '2024-01-11 11:20:00'
  },
  {
    id: 6,
    code: 'P006',
    name: '乐事薯片',
    category: 'food',
    brand: '乐事',
    price: 8.50,
    costPrice: 6.00,
    stock: 300,
    unit: '包',
    description: '经典原味薯片',
    status: 'inactive',
    createTime: '2024-01-10 09:30:00'
  },
  {
    id: 7,
    code: 'P007',
    name: '华为Mate60',
    category: 'electronics',
    brand: '华为',
    price: 6999.00,
    costPrice: 5600.00,
    stock: 25,
    unit: '台',
    description: '国产高端手机',
    status: 'active',
    createTime: '2024-01-09 14:15:00'
  },
  {
    id: 8,
    code: 'P008',
    name: '兰蔻小黑瓶',
    category: 'beauty',
    brand: '兰蔻',
    price: 899.00,
    costPrice: 650.00,
    stock: 80,
    unit: '瓶',
    description: '明星精华产品',
    status: 'active',
    createTime: '2024-01-08 10:45:00'
  }
]

// 获取分类类型
const getCategoryType = (category) => {
  const typeMap = {
    food: 'success',
    clothing: 'warning',
    electronics: 'primary',
    home: 'info',
    beauty: 'danger'
  }
  return typeMap[category] || 'info'
}

// 获取分类文本
const getCategoryText = (category) => {
  const textMap = {
    food: '食品饮料',
    clothing: '服装鞋帽',
    electronics: '电子产品',
    home: '家居用品',
    beauty: '美妆护肤'
  }
  return textMap[category] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  return status === 'active' ? 'success' : 'danger'
}

// 获取状态文本
const getStatusText = (status) => {
  return status === 'active' ? '上架' : '下架'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    code: '',
    name: '',
    category: '',
    status: ''
  })
  handleSearch()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增商品'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑商品'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看功能开发中...')
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 批量操作
const handleBatchUpdate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要操作的商品')
    return
  }
  ElMessage.info('批量操作功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    category: '',
    brand: '',
    price: 0,
    costPrice: 0,
    stock: 0,
    unit: '',
    description: '',
    status: 'active'
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.retail-products {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .search-form {
    background: white;
    padding: 20px;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    margin-bottom: 20px;
  }
  
  .button-group {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }
  
  .card {
    background: white;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    padding: 20px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 